package com.paipai.Filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.paipai.jwtproperty.JwtProperties;
import com.paipai.utils.CookieUtils;
import com.paipai.utils.JwtUtils;
import com.paipai.utils.UserInfo;

@Component
public class LoginFilter  extends ZuulFilter{
	@Autowired
	 private JwtProperties jwp;
	
	
	//是否拦截
	@Override
	public boolean shouldFilter() {
		//request上下文对象
		RequestContext context = RequestContext.getCurrentContext();
		HttpServletRequest req = context.getRequest();
		String URI = req.getRequestURI();
		
		//黑名单
		List<String> list = new ArrayList<String>();
		list.add("/api/product/Bidding/executeBidding");
		list.add("/api/order/");
		
		for (String str : list) {
			if(URI.contains(str)) {
				return true;
			}
		}
		
		return false;
	}
	//拦截器优先级
	@Override
	public int filterOrder() {
		return 1;
	}
	@Override
	public String filterType() {
		//pre 前置拦截
		return "pre";
	}
	
	//
	@Override
	public Object run() throws ZuulException {
		
		//request上下文对象
		RequestContext context = RequestContext.getCurrentContext();
		HttpServletRequest req = context.getRequest();
		
		String url = req.getRequestURL().toString();
		System.out.println("url: "+url);
		
		String cookieValue = CookieUtils.getCookieValue(req, "loginToken");
		try {
			UserInfo token = JwtUtils.getInfoFromToken(cookieValue, jwp.getPublicKey());
		} catch (Exception e) {
			System.out.println("token解析失败");
			
			context.setSendZuulResponse(false);
	        //设置提示
	        context.setResponseBody("403");
			
			//e.printStackTrace();
		}
		return null;
	}
	



	

	

}
